<template>
  <div class="proStirageOrd" @click.stop="aotuTab=false">
    <div style="margin-bottom: 10px">
      <jc-button
        :btn-arr="['save', 'remove', 'pass', 'sub', 'option', 'reload', 'list']"
        :disab-arr="[isDisabled && 'save', 'com1', 'com2', 'cancel', 'using', 'freeze']"
        :fbillno="production.fbillno"
        :list="'/operationERP'"
        @refresh="getSCLLinfo"
        @save="proSave"
        @submit="proSave(1)"
        @noSubmit="submit(2)"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @forbidden="using(1)"
        @startUsing="using(2)"
        @del="delStirage"
        @toExcel="handleExport"
      />
    </div>
    <el-tabs v-model="activeName" @tab-click="handleOther">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form ref="purchaseRef" :model="production" label-width="4.68vw">
          <el-form-item :label="$t('market.documentstatus')">
            <!--            <el-input v-model.trim="production.statusName" disabled />-->
            <el-tag :type="production.stateColor">
              {{ production.fdocumentstatus }}
            </el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.billNo')">
            <el-input v-model.trim="production.fbillno" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.backupdate')">
            <el-input v-model.trim="production.fbackupdate" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.note')">
            <el-input v-model.trim="production.fnote" :disabled="isDisabled" />
          </el-form-item>
        </el-form>
        <div>
          <div style="display: flex;margin-top: 10px">
            <el-button size="mini" :disabled="isDisabled" @click="newHang">{{ $t('btn.newHang') }}<!--新增行--></el-button>
            <el-button size="mini" :disabled="isDisabled" style="margin-bottom: 5px;" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
            <el-form ref="purchaseRef" :model="detailData" label-width="4.68vw">
              <el-form-item :label="$t('market.fmaterial')">
                <el-input v-model.trim="detailData.fnumber" />
              </el-form-item>
              <el-form-item :label="$t('shop.fname2')">
                <el-input v-model.trim="detailData.fname" />
              </el-form-item>
              <el-form-item :label="$t('shop.fspecificaTion')">
                <el-input v-model.trim="detailData.fspecificaTion" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="mini" @click="getSCLLinfo">{{ $t('btn.search') }}<!--新增行--></el-button>
              </el-form-item>
            </el-form>
          </div>
          <jc-table
            :table-data="tableData"
            :table-header="tableHeader"
            :table-height="tableHeight"
            :get-summaries="getSummaries"
            show-summary
            table-selection
            @selectionChange="handleSelectAll"
            @rowClick="rowClick"
          >
            <!-- 仓库 -->
            <template v-slot:text2Slot="col">
              <el-input
                v-model.trim="col.scope.row.fstockDesc"
                size="mini"
              >
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="handleGetck(col.scope.$index)"
                />
              </el-input>
            </template>
            <!--物料编码-->
            <template v-slot:orderSlot="col">
              <el-input
                v-model.trim="col.scope.row.fnumber"
                size="mini"
                @input="getAtuo(col.scope.$index, col.scope.row.fnumber)"
              >
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="handleGetMateriel(col.scope.row, col.scope.$index)"
                />
              </el-input>
              <div v-if="aotuTab && indexSelf === col.scope.$index" :class="indexSelf<7 ? 'tabPosit': 'tabPosit1'">
                <number-code :fnumber="fnumber" @material="materialData" />
              </div>
            </template>
            <template v-slot:btnState="col">
              <el-input-number v-model="col.scope.row.fcountqty" size="mini" :disabled="isDisabled" />
            </template>
          </jc-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')" name="log">
        <jc-marker
          ref="log"
          :fnumber="production.fbillno"
          other-height="68vh"
          :other-url-object="otherUrlObject"
        />
      </el-tab-pane>
    </el-tabs>
    <!--物料弹窗-->
    <material v-if="isMateria" @material="materialData" />
    <!--仓库-->
    <selectCK
      v-if="seleceVisiblit"
      :msg="1"
      @client="selectData"
    />
  </div>
</template>

<script>
import operability from '@/mixin/Operability'
import jcButton from '@/components/Button'
import { notoMxBmina, toMxBmina } from '@/components/ToMxamineState'
import jcMarker from '@/components/marker'
import jumpMateriel from '@/components/JumpMateriel'
import {
  deleteStkcountInPut, deleteStkcountInPutDetails, getStkcountInPutById,
  stkCountInPutAudit,
  stkCountInPutAuSubmit, stkCountInPutClose,
  stkCountInPutSubmit,
  stkCountInPutUnAudit, stkCountInPutUnClose, updateStkcountInPut
} from '@/api/repertory/stock'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'

export default {
  name: 'EditMaterial',
  components: {
    jcButton,
    jcMarker,
    selectCK: () => import('@/views/production/collect/components/seleceCK'),
    material: () => import('@/views/market/marketManage/createMarkerOrder/components/material'),
    numberCode: () => import('@/components/NumberCode')
  },
  mixins: [operability, jumpMateriel],
  props: {
    list: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      isMateria: false,
      aotuTab: false,
      upDownVis: false,
      cha: '',
      fentryData: [],
      targerName: 'proStirageOrder',
      activeName: 'first',
      production: {},
      detailData: {},
      fnumber: '',
      isDisabled: false,
      seleceVisiblit: false, // 仓库
      indexSelf: 0,
      otherUrlObject: {},
      tableAudit: [],
      tableHeight: '74vh',
      tableData: [],
      tableHeader: [
        { label: this.$t('market.stockname'), prop: 'fstockDesc', type: 'text2' },
        { label: this.$t('market.stockNumber'), prop: 'fstockCode' },
        { label: this.$t('market.fmodel2'), prop: 'fmodel' },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'fnumber', width: '160' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecification' },
        { label: this.$t('shop.unit'), prop: 'funit' },
        { label: this.$t('market.acctqty'), prop: 'facctqty' },
        { label: this.$t('market.countqty'), type: 'state', prop: 'fcountqty' },
        { label: this.$t('market.gainqty'), prop: 'fgainqty' },
        { label: this.$t('market.flossqty'), prop: 'flossqty' },
        { label: this.$t('market.counterror'), prop: 'fcounterror' },
        { label: this.$t('market.note'), prop: 'fnote', width: '200' }
      ],
      delArr: []
    }
  },
  created() {
    if (this.$route.params.id) {
      this.getSCLLinfo()
    }
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 270px)' : '72vh'
  },
  methods: {
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.indexSelf = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber = fnumber
      }, 600)
    },
    // 盘点作业数据
    getSCLLinfo() {
      const DATA = {
        fid: this.$route.params.id,
        ...this.detailData
      }
      getStkcountInPutById(DATA).then(res => {
        if (res.code === 0) {
          this.production = toMxBmina(res.data)
          this.otherUrlObject = res.data
          this.tableData = res.data.details
          this.isDisabled = this.production.fdocumentstatus === this.$t('market.state1') || this.production.fdocumentstatus === this.$t('market.state2')
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 保存
    proSave(ev) {
      const DATA = {
        ...notoMxBmina(this.production),
        details: this.tableData,
        delArr: this.delArr
      }
      updateStkcountInPut(DATA).then(res => {
        if (res.code === 0) {
          this.delArr = []
          ev === 1 ? this.submit(1) : this.getSCLLinfo()
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 打开物料弹窗
    handleGetMateriel(row, index) {
      this.isMateria = true
      this.indexSelf = index
    },
    // 物料数据
    materialData(item) {
      if (item.fmaterialId) {
        const items = this.tableData[this.indexSelf]
        items.fmaterialid = item.fmaterialId
        items.fnumber = item.fnumber
        items.fname = item.fname
        items.fdescripTion = item.fdescripTion
        items.fspecification = item.fspecificaTion
        items.funitid = item.funitId
        items.funit = item.funit
        items.fmodel = item.fmodel
        items.fstockDesc = item.fstock
        items.fstockid = item.fstockId
      }
      this.aotuTab = false
      this.isMateria = false
    },
    handleGetck(index) {
      this.seleceVisiblit = true
      this.indexSelf = index
    },
    // 选择仓库
    selectData(ev) {
      if (ev.fstockId) {
        const item = this.tableData[this.indexSelf]
        item.fstockCode = this.fnumber
        item.fstockDesc = ev.fname
        item.fstockid = ev.fstockId
      }
      this.seleceVisiblit = false
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = {
        Numbers: [this.production.fbillno]
      }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString: true,
            type: 'error'
          })
          return
        }
        this.getSCLLinfo()
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 提交
    async submit(ev) {
      const api = ev === 1 ? stkCountInPutSubmit : stkCountInPutAuSubmit
      this.toExamineFun(api)
    },
    // 审核
    async audit(ev) {
      const api = ev === 1 ? stkCountInPutAudit : stkCountInPutUnAudit
      this.toExamineFun(api)
    },
    // 关闭
    async using(ev) {
      const api = ev === 1 ? stkCountInPutClose : stkCountInPutUnClose
      this.toExamineFun(api)
    },
    // 删除
    delStirage() {
      this.$confirm('确定要删除该订单么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const DATA = { Numbers: [this.production.fbillno] }
        deleteStkcountInPut(DATA).then(res => {
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          // 跳转到修改页面
          this.$router.push({ path: '/operationERP' })
        })
      })
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          const list = this.tableData
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, 'ERP盘点作业')
        }
      })
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    newHang() {
      this.tableData.push({
        fentryid: 0,
        fstockDesc: '',
        fstockCode: '',
        fmodel: '',
        fnumber: '',
        fname: '',
        fspecification: '',
        funit: '',
        facctqty: 0,
        fcountqty: 0,
        fgainqty: 0,
        flossqty: 0,
        fcounterror: 0,
        fnote: ''
      })
    },
    // 全选
    handleSelectAll(val) {
      this.EntryIds = []
      val.forEach(res => {
        this.EntryIds.push(res.fentryid)
      })
    },
    // 删除行
    delHang() {
      this.$confirm('确定要删除么', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStkcountInPutDetails({ EntryIds: this.EntryIds }).then(res => {
          if (res.code === 0) {
            this.getSCLLinfo()
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    },
    // 操作记录
    handleOther(tab) {
      if (tab.name === 'log') {
        this.$refs.log.otherlog()
      }
    }
  }
}
</script>

<style lang="scss" scope>
.proStirageOrd {
  @include listBom;
  .el-tabs {
    .el-form {
      display: flex;
      flex-wrap: wrap;
      .el-input .el-input__inner {
        height: 30px;
        line-height: 30px;
      }
      .el-form-item {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 35px;
        width: 275px;
        margin-bottom: 0.46vh;
        .btnType {
          margin-right: 5px;
        }

        .el-date-editor.el-input {
          width: 100% !important;
        }

        .el-select {
          width: 100%;
        }
      }
    }
  }
  .tabPosit {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: 3.5vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 99999!important;
  }
  .tabPosit1 {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: -25.69vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 9999;
  }
}
</style>
